package com.zbl.zblproject.core.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.base.Preconditions;
import com.zbl.zblproject.core.entity.AdminUser;
import com.zbl.zblproject.core.entity.RechargeLog;
import com.zbl.zblproject.core.entity.UserAddress;
import com.zbl.zblproject.core.mapper.AdminUserMapper;
import com.zbl.zblproject.core.mapper.RechargeLogMapper;
import com.zbl.zblproject.core.mapper.UserAddressMapper;
import com.zbl.zblproject.core.service.UserService;
import com.zbl.zblproject.core.utils.StringUtil;
import com.zbl.zblproject.core.utils.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author youlanqiang
 * @version 1.0
 * @date 2018/11/13
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private AdminUserMapper adminUserMapper;

    @Autowired
    private UserAddressMapper userAddressMapper;

    @Autowired
    private RechargeLogMapper rechargeLogMapper;


    @Override
    public List<AdminUser> searchUser(String name) {
        QueryWrapper<AdminUser> userWrapper = new QueryWrapper<>();
        userWrapper.select("user_id", "user_name", "logistics", "balance");
        if(!StringUtil.isNullOrEmpty(name)){
            userWrapper.like("user_name", name);
        }
        userWrapper.gt("user_id", 4).orderByDesc("user_name");
        List<AdminUser> users = adminUserMapper.selectList(userWrapper);
        users.forEach((x)->{
            x.setAddressList(userAddressMapper.selectAddressesByUserId(x.getUserId()));
        });
        return users;
    }


    @Override
    public boolean recharge(int userId, int operatorId, double price) {
        if(price <= 0){
            throw new RuntimeException("充值金额太少!");
        }
        BigDecimal money = BigDecimal.valueOf(price);
        AdminUser user = adminUserMapper.selectById(userId);
        Preconditions.checkNotNull(user, "未查询到用户!");
        RechargeLog log = new RechargeLog();
        log.setBeforeMoney(user.getBalance());
        log.setMoney(money);
        log.setTime(LocalDateTime.now());
        log.setUserId(userId);
        log.setOperatorName(adminUserMapper.selectNameById(operatorId));
        log.setMode(0);

        user.setBalance(user.getBalance().add(money));
        rechargeLogMapper.insert(log);
        return adminUserMapper.updateById(user) == 1;
    }

    @Override
    public IPage<RechargeLog> logPage(int userId, int current, int size) {
        QueryWrapper<RechargeLog> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId).eq("mode", 0);
        IPage<RechargeLog> page = new Page<>(current, size);
        page  = rechargeLogMapper.selectPage(page, wrapper);
        page.getRecords().forEach(x->{
            x.setAdminUser(adminUserMapper.selectById(x.getUserId()));
        });
        return page;
    }

    @Override
    public IPage<RechargeLog> logPage(int current, int size, String start, String end) {
        QueryWrapper<RechargeLog> wrapper = new QueryWrapper<>();
        wrapper.eq("mode", 0);
        if (!StringUtil.isNullOrEmpty(start)) {
            wrapper.ge("time", TimeUtil.parseTime(start));
        }
        if (!StringUtil.isNullOrEmpty(end)) {
            wrapper.le("time", TimeUtil.parseTime(end));
        }
        IPage<RechargeLog> page = new Page<>(current, size);
        page = rechargeLogMapper.selectPage(page, wrapper);
        page.getRecords().forEach(x->{
            x.setAdminUser(adminUserMapper.selectById(x.getUserId()));
        });
        return page;
    }

    @Override
    public List<JSONObject> list() {
        //this.user.userId=this.userList[index].user_id;
        //this.user.userCode=this.userList[index].user_code;
        //this.user.userName=this.userList[index].user_name;
        //this.user.address=this.userList[index].address;
        //this.user.mobile=this.userList[index].mobile;
        //this.user.email=this.userList[index].email;
        //this.user.logistics=this.userList[index].logistics;
        //this.user.balance=this.userList[index].balance;
        List<JSONObject> array = new ArrayList<>();
        for(AdminUser user : adminUserMapper.selectList(null)){
            JSONObject object = new JSONObject();
            object.put("user_id", user.getUserId());
            object.put("user_code", user.getUserCode());
            object.put("user_name", user.getUserName());
            UserAddress address = userAddressMapper.selectOneByUserId(user.getUserId());
            if(address!=null){
                object.put("address", address.getAddress());
                object.put("mobile", address.getMobile());
            }else{
                object.put("address", "");
                object.put("mobile", "");
            }
            object.put("email", user.getEmail());
            object.put("logistics", user.getLogistics());
            object.put("balance", user.getBalance());
            array.add(object);
        }
        return array;
    }
}
